<template>
  <div class="analysis-container">
    <el-row :gutter="20">
      <el-col :span="5">
        <el-card class="query-panel">
          <template #header>
            <div class="card-header">
              <span>查询条件</span>
            </div>
          </template>
          <el-form :model="queryForm" label-width="80px">
            <el-form-item label="布局方式">
              <el-select v-model="queryForm.layout" placeholder="请选择布局方式">
                <el-option label="地理布局" value="geographic" />
                <el-option label="层次布局" value="hierarchical" />
                <el-option label="辐射布局" value="radial" />
                <el-option label="力导向布局" value="force" />
              </el-select>
            </el-form-item>
            <el-form-item label="地区">
              <el-select v-model="queryForm.region" placeholder="请选择地区">
                <el-option label="全部" value="all" />
                <el-option label="台北地区" value="taipei" />
                <el-option label="台中地区" value="taichung" />
                <el-option label="台南地区" value="tainan" />
                <el-option label="花莲地区" value="hualien" />
                <el-option label="高雄地区" value="kaohsiung" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery" :loading="loading">查询</el-button>
              <el-button type="text" @click="resetHighlight" :disabled="!isHighlighted">重置高亮</el-button>
              <el-button type="text" @click="handleInitTestData" :disabled="loading">初始化测试数据</el-button>
            </el-form-item>
          </el-form>
          
          <!-- 显示错误信息 -->
          <div v-if="error" class="error-message">
            <el-alert
              :title="error"
              type="error"
              show-icon
              :closable="true"
              @close="error = ''"
            />
          </div>
          
          <div v-if="tracedFacility" class="facility-detail">
            <div class="facility-title">
              <strong>{{ tracedFacility.name }}</strong>
              <el-tag :type="getTypeTag(tracedFacility.facility_type)" size="small">{{ getFacilityTypeName(tracedFacility.facility_type) }}</el-tag>
            </div>
            <div class="facility-info">
              <div class="info-item">
                <span class="label">储量/产能:</span>
                <span class="value">{{ tracedFacility.value }} 万吨</span>
              </div>
              <div class="info-item">
                <span class="label">区域:</span>
                <span class="value">{{ getRegionName(tracedFacility.region) }}</span>
              </div>
              <div class="info-item">
                <span class="label">连接数量:</span>
                <span class="value">{{ getConnectionCount(tracedFacility.id) }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="19">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="map-container">
              <template #header>
                <div class="card-header">
                  <span>油料设施分布图</span>
                  <div class="legend">
                    <div class="legend-item">
                      <span class="color-dot" style="background-color: #1976D2;"></span>
                      <span>原油进口设施</span>
                    </div>
                    <div class="legend-item">
                      <span class="color-dot" style="background-color: #D32F2F;"></span>
                      <span>炼油厂</span>
                    </div>
                    <div class="legend-item">
                      <span class="color-dot" style="background-color: #FFA000;"></span>
                      <span>区域存储油库</span>
                    </div>
                    <div class="legend-item">
                      <span class="color-dot" style="background-color: #388E3C;"></span>
                      <span>机场油库</span>
                    </div>
                  </div>
                </div>
              </template>
              <div id="mapChart" class="chart" ref="mapChartRef"></div>
              <div v-if="loading" class="loading-overlay">
                <div class="spinner"></div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="12">
            <el-card class="network-container">
              <template #header>
                <div class="card-header">
                  <span>油料供应网络关系图</span>
                  <div class="layout-switch">
                    <span class="layout-label">布局：{{ getLayoutName(queryForm.layout) }}</span>
                  </div>
                </div>
              </template>
              <div id="networkChart" class="chart" ref="networkChartRef"></div>
              <div v-if="loading" class="loading-overlay">
                <div class="spinner"></div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import 'leaflet/dist/leaflet.css'
import L from 'leaflet'
import { 
  getNetworkData, 
  traceSupplyChain, 
  getInitialData, 
  initTestData 
} from '@/api/oil-supply'

// 修复Leaflet图标在webpack中的问题
delete L.Icon.Default.prototype._getIconUrl
L.Icon.Default.mergeOptions({
  iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
  iconUrl: require('leaflet/dist/images/marker-icon.png'),
  shadowUrl: require('leaflet/dist/images/marker-shadow.png')
})

// 查询表单
const queryForm = ref({
  layout: 'force',
  region: 'all'
})

// 加载状态
const loading = ref(false)
// 错误状态
const error = ref('')

// 图表实例
let mapInstance = null
let markersLayer = null
let networkChart = null

// 数据
const networkData = ref({
  nodes: [],
  links: [],
  categories: []
})

// 追踪的设施
const tracedFacility = ref(null)

// 是否高亮状态
const isHighlighted = ref(false)

// 图表DOM引用
const mapChartRef = ref(null)
const networkChartRef = ref(null)

// 地区名称映射
const regionNames = {
  all: '全部',
  taipei: '台北地区',
  taichung: '台中地区',
  tainan: '台南地区',
  hualien: '花莲地区',
  kaohsiung: '高雄地区'
}

// 布局名称映射
const layoutNames = {
  geographic: '地理布局',
  hierarchical: '层次布局',
  radial: '辐射布局',
  force: '力导向布局'
}

// 获取布局名称
const getLayoutName = (layout) => {
  return layoutNames[layout] || layout;
}

// 获取区域名称
const getRegionName = (region) => {
  return regionNames[region] || region;
}

// 获取设施类型的颜色
const getFacilityTypeColor = (facilityType) => {
  const colors = {
    'import': '#1976D2',    // 蓝色 - 原油进口设施
    'refinery': '#D32F2F',  // 红色 - 炼油厂
    'storage': '#FFA000',   // 橙色 - 区域存储油库
    'airport': '#388E3C'    // 绿色 - 机场油库
  }
  return colors[facilityType] || '#9E9E9E' // 默认灰色
}

// 获取设施类型名称
const getFacilityTypeName = (facilityType) => {
  const typeNames = {
    'import': '原油进口设施',
    'refinery': '炼油厂',
    'storage': '区域存储油库',
    'airport': '机场油库'
  }
  return typeNames[facilityType] || facilityType
}

// 获取设施类型对应的标签类型
const getTypeTag = (facilityType) => {
  const tagTypes = {
    'import': 'primary',
    'refinery': 'danger',
    'storage': 'warning',
    'airport': 'success'
  }
  return tagTypes[facilityType] || 'info'
}

// 获取设施的颜色
const getFacilityColor = (type) => {
  const colorMap = {
    'import': '#1976D2',    // 蓝色 - 原油进口设施
    'refinery': '#D32F2F',  // 红色 - 炼油厂
    'storage': '#FFA000',   // 橙色 - 区域存储油库
    'airport': '#388E3C'    // 绿色 - 机场油库
  }
  return colorMap[type] || '#9E9E9E'
}

// 获取连接数量
const getConnectionCount = (facilityId) => {
  if (!networkData.value || !networkData.value.links) {
    return 0;
  }
  
  return networkData.value.links.filter(link => 
    link.source === facilityId || 
    link.target === facilityId ||
    (link.source && link.source.id === facilityId) || 
    (link.target && link.target.id === facilityId)
  ).length;
}

// 获取运输方式名称
const getTransportationName = (transportationType) => {
  const transportationNames = {
    'pipeline': '管道运输',
    'ship': '船舶运输',
    'truck': '卡车运输',
    'train': '铁路运输'
  }
  return transportationNames[transportationType] || transportationType
}

// 获取节点名称（用于连接提示）
const getNodeName = (node) => {
  if (typeof node === 'object') {
    return node.name
  }
  const foundNode = networkData.value?.nodes?.find(n => n.id === node)
  return foundNode ? foundNode.name : `节点${node}`
}

// 初始化地图
const initMap = () => {
  try {
    // 如果已存在地图实例，则先清除
    if (mapInstance) {
      mapInstance.remove()
    }
    
    // 检查DOM元素是否存在
    const mapContainer = document.getElementById('mapChart')
    if (!mapContainer) {
      console.error('地图容器DOM元素不存在')
      return
    }
    
    console.log('正在初始化地图...')
    
    // 创建地图
    mapInstance = L.map('mapChart', {
      center: [23.7, 121.0],  // 台湾中心位置
      zoom: 7,
      zoomControl: true
    })
    
    // 创建并添加离线地图图层
    const offlineLayer = L.tileLayer('/assets/map-of-taiwan/gaode_map/{z}/{x}/{y}.png', {
      minZoom: 8,
      maxZoom: 11,
      tileSize: 256,
      attribution: '高德地图离线数据',
      errorTileUrl: '',
      noWrap: true,
      bounds: L.latLngBounds(
        L.latLng(20.63278, 119.53125),  // 西南角
        L.latLng(25.79989, 122.34375)   // 东北角
      ),
      tms: false,
      crossOrigin: true,
      subdomains: '',
      detectRetina: false
    })
    
    // 使用离线地图数据
    offlineLayer.addTo(mapInstance)
    
    // 创建标记图层
    markersLayer = L.layerGroup().addTo(mapInstance)
    
    console.log('地图初始化成功')
  } catch (err) {
    console.error('初始化地图失败:', err)
    error.value = `初始化地图失败: ${err.message || '未知错误'}`
  }
}

// 更新地图标记
const updateMapMarkers = (nodes, highlightedIds = []) => {
  try {
    if (!mapInstance || !nodes || !Array.isArray(nodes)) {
      console.error('更新地图标记失败: 地图实例或节点数据无效')
      return
    }
    
    // 清除现有标记
    if (markersLayer) {
      markersLayer.clearLayers()
    } else {
      markersLayer = L.layerGroup().addTo(mapInstance)
    }
    
    // 是否有高亮状态
    const isHighlighting = highlightedIds && highlightedIds.length > 0
    
    // 添加新标记
    nodes.forEach(node => {
      // 检查节点是否有经纬度
      if ((node.latitude === undefined || node.longitude === undefined) && 
          (node.lat === undefined || node.lng === undefined) &&
          (node.y === undefined || node.x === undefined)) {
        console.warn(`节点 ${node.id} (${node.name}) 缺少经纬度信息`)
        return
      }
      
      // 确定经纬度值
      let lat, lng
      if (node.latitude !== undefined && node.longitude !== undefined) {
        lat = node.latitude
        lng = node.longitude
      } else if (node.lat !== undefined && node.lng !== undefined) {
        lat = node.lat
        lng = node.lng
      } else if (node.y !== undefined && node.x !== undefined) {
        // 有些数据可能用x/y表示经纬度
        lat = node.y
        lng = node.x
      }
      
      // 创建图标
      const isHighlighted = highlightedIds.includes(node.id)
      const iconSize = isHighlighted ? [35, 35] : [25, 25]
      const iconColor = getFacilityTypeColor(node.facility_type)
      
      // 设置图标颜色和样式
      const markerIcon = L.divIcon({
        className: `custom-marker ${isHighlighted ? 'highlighted' : ''}`,
        html: `<div style="background-color: ${iconColor}; width: 100%; height: 100%; border-radius: 50%; border: 2px solid white; opacity: ${isHighlighting && !isHighlighted ? 0.3 : 1};"></div>`,
        iconSize: iconSize
      })
      
      // 创建标记
      const marker = L.marker([lat, lng], { icon: markerIcon })
      
      // 添加气泡
      marker.bindPopup(`
        <div class="facility-popup">
          <h4>${node.name}</h4>
          <p>类型: ${getFacilityTypeName(node.facility_type)}</p>
          <p>储量/产能: ${node.value} 万吨</p>
          <p>区域: ${getRegionName(node.region)}</p>
        </div>
      `, { className: 'facility-tooltip' })
      
      // 点击标记事件
      marker.on('click', () => {
        // 高亮设施
        highlightFacility(node.id)
      })
      
      // 添加到图层
      marker.addTo(markersLayer)
    })
    
  } catch (err) {
    console.error('更新地图标记失败:', err)
  }
}

// 初始化网络图表
const initNetworkChart = () => {
  try {
    // 如果已经存在实例，先销毁
    if (networkChart) {
      networkChart.dispose()
      networkChart = null
    }
    
    // 检查DOM元素是否存在
    const chartContainer = document.getElementById('networkChart')
    if (!chartContainer) {
      console.error('网络图表容器DOM元素不存在')
      return
    }
    
    console.log('正在初始化网络图...')
    
    // 创建ECharts实例
    networkChart = echarts.init(chartContainer)
    
    // 设置基础配置
    const option = {
      title: {
        text: '油料供应网络关系图',
        left: 'center',
        top: 'top',
        textStyle: {
          fontSize: 16,
          color: '#303133'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: function(params) {
          if (params.dataType === 'node') {
            return `
              <div style="font-weight:bold">${params.data.name}</div>
              <div>类型: ${getFacilityTypeName(params.data.facility_type)}</div>
              <div>区域: ${getRegionName(params.data.region)}</div>
              <div>储量/产能: ${params.data.value} 万吨</div>
            `
          } else {
            // 连接的工具提示
            return `从 ${getNodeName(params.data.source)} 到 ${getNodeName(params.data.target)}`
          }
        }
      },
      legend: {
        show: true,
        data: ['原油进口设施', '炼油厂', '区域存储油库', '机场油库'],
        bottom: 10,
        left: 'center',
        selectedMode: false
      },
      animationDurationUpdate: 1500,
      animationEasingUpdate: 'quinticInOut',
      series: [{
        type: 'graph',
        layout: queryForm.value.layout,
        force: {
          repulsion: 1000,
          gravity: 0.1,
          edgeLength: [50, 200]
        },
        roam: true,
        zoom: 1,
        label: {
          show: true,
          position: 'right',
          formatter: '{b}'
        },
        lineStyle: {
          color: '#bbb',
          width: 2,
          opacity: 0.5,
          curveness: 0.3
        },
        emphasis: {
          lineStyle: {
            color: '#409EFF',
            width: 4
          },
          focus: 'adjacency'
        },
        edgeSymbol: ['none', 'arrow'],
        edgeLabel: {
          show: false
        },
        data: [],
        links: [],
        categories: [
          { name: '原油进口设施' },
          { name: '炼油厂' },
          { name: '区域存储油库' },
          { name: '机场油库' }
        ]
      }]
    };
    
    // 应用配置
    networkChart.setOption(option);
    
    // 注册点击事件
    networkChart.on('click', params => {
      if (params.dataType === 'node') {
        // 点击节点高亮对应供应链
        highlightFacility(params.data.id);
      }
    });
    
    console.log('网络图初始化成功');
  } catch (err) {
    console.error('初始化网络图表失败:', err);
    error.value = `初始化网络图表失败: ${err.message || '未知错误'}`;
  }
};

// 更新网络图表
const updateNetworkChart = (data, highlightedIds = []) => {
  try {
    if (!networkChart) {
      console.error('网络图表实例不存在')
      return
    }
    
    if (!data || !data.nodes || !data.links) {
      console.error('无效的网络数据')
      return
    }
    
    console.log('正在更新网络图...')
    
    // 是否处于高亮状态
    const isHighlighting = highlightedIds && highlightedIds.length > 0
    
    // 节点数据处理
    const nodes = data.nodes.map(node => {
      // 高亮状态处理
      const isHighlighted = !isHighlighting || highlightedIds.includes(node.id)
      const opacity = isHighlighted ? 1 : 0.3
      
      // 确保节点有所有必要属性
      return {
        ...node,
        itemStyle: {
          color: getFacilityTypeColor(node.facility_type),
          opacity: opacity,
          borderWidth: 2,
          borderColor: '#fff'
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{b}',
          fontSize: 12,
          color: '#303133'
        },
        symbolSize: node.symbolSize || (20 + Math.min(node.value / 10, 30)),
        emphasis: {
          scale: true,
          label: {
            show: true,
            fontWeight: 'bold',
            fontSize: 14
          }
        }
      }
    })
    
    // 连接数据处理
    const links = data.links.map(link => {
      let isHighlighted = false
      
      // 如果有高亮节点，检查连接是否连接到高亮节点
      if (isHighlighting) {
        const sourceId = typeof link.source === 'object' ? link.source.id : link.source
        const targetId = typeof link.target === 'object' ? link.target.id : link.target
        isHighlighted = highlightedIds.includes(sourceId) && highlightedIds.includes(targetId)
      } else {
        isHighlighted = true
      }
      
      return {
        ...link,
        symbolSize: [5, 8],
        lineStyle: {
          width: isHighlighted ? 3 : 1,
          opacity: isHighlighted ? 0.9 : 0.3,
          color: isHighlighted ? '#409EFF' : '#bbb',
          curveness: 0.2,
          type: 'solid'
        },
        label: {
          show: true,
          formatter: link.transportation ? getTransportationName(link.transportation) : '',
          fontSize: 10
        },
        emphasis: {
          lineStyle: {
            width: 4,
            color: '#409EFF'
          }
        }
      }
    })
    
    // 更新图表配置
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: function(params) {
          if (params.dataType === 'node') {
            return `
              <div style="font-weight:bold">${params.data.name}</div>
              <div>类型: ${getFacilityTypeName(params.data.facility_type)}</div>
              <div>区域: ${getRegionName(params.data.region)}</div>
              <div>储量/产能: ${params.data.value} 万吨</div>
            `
          } else {
            return `从 ${getNodeName(params.data.source)} 到 ${getNodeName(params.data.target)}`
          }
        }
      },
      legend: {
        show: true,
        data: ['原油进口设施', '炼油厂', '区域存储油库', '机场油库'],
        bottom: 10,
        left: 'center',
        selectedMode: false,
        textStyle: {
          fontSize: 12
        }
      },
      animationDurationUpdate: 1500,
      animationEasingUpdate: 'quinticInOut',
      series: [{
        type: 'graph',
        layout: queryForm.value.layout,
        force: {
          repulsion: 1500,
          gravity: 0.1,
          edgeLength: [100, 300],
          layoutAnimation: true
        },
        roam: true,
        draggable: true,
        zoom: 1,
        center: ['50%', '50%'],
        symbol: 'circle',
        data: nodes,
        links: links,
        categories: data.categories || [
          { name: '原油进口设施' },
          { name: '炼油厂' },
          { name: '区域存储油库' },
          { name: '机场油库' }
        ],
        emphasis: {
          focus: 'adjacency',
          scale: true
        },
        edgeSymbol: ['circle', 'arrow'],
        edgeSymbolSize: [4, 8],
        lineStyle: {
          color: '#bbb',
          curveness: 0.2,
          width: 2
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{b}',
          fontSize: 12
        }
      }]
    }
    
    // 如果是地理布局模式，添加经纬度映射
    if (queryForm.value.layout === 'geographic') {
      nodes.forEach(node => {
        if (node.latitude !== undefined && node.longitude !== undefined) {
          node.x = node.longitude
          node.y = node.latitude
        } else if (node.lat !== undefined && node.lng !== undefined) {
          node.x = node.lng
          node.y = node.lat
        }
      })
    }
    
    // 应用配置更新
    networkChart.setOption(option, true)
    
    console.log('网络图更新成功')
  } catch (err) {
    console.error('更新网络图表失败:', err)
    error.value = `更新网络图表失败: ${err.message || '未知错误'}`
  }
}

// 加载网络数据
const loadNetworkData = async () => {
  loading.value = true
  error.value = ''
  
  try {
    console.log('Loading network data with params:', { region: queryForm.value.region })
    const response = await getNetworkData({ region: queryForm.value.region })
    console.log('Network data response:', response)
    
    let responseData = null
    // 处理两种可能的响应结构
    if (response.data !== undefined) {
      // 结构: { data: { nodes, links, categories } }
      responseData = response.data
    } else {
      // 结构: { nodes, links, categories }
      responseData = response
    }
    
    // 验证数据格式
    if (!responseData || !Array.isArray(responseData.nodes) || !Array.isArray(responseData.links)) {
      throw new Error('无效的网络数据格式')
    }
    
    // 数据后处理 - 确保每个节点有正确的属性
    responseData.nodes = responseData.nodes.map(node => {
      // 确保节点有category属性
      if (node.category === undefined && node.facility_type !== undefined) {
        const categoryMap = {
          'import': 0,
          'refinery': 1,
          'storage': 2,
          'airport': 3
        }
        node.category = categoryMap[node.facility_type] || 0
      }
      
      // 确保节点有value属性
      if (node.value === undefined && node.capacity !== undefined) {
        node.value = node.capacity
      }
      
      return node
    })
    
    // 更新网络数据
    networkData.value = responseData
    
    // 如果没有数据，显示提示
    if (responseData.nodes.length === 0) {
      ElMessage.warning('未找到任何油料设施数据')
    } else {
      // 更新图表
      await nextTick()
      // 确保图表实例初始化
      if (!mapInstance) {
        initMap()
      }
      if (!networkChart) {
        initNetworkChart()
      }
      
      // 更新地图标记和网络图
      updateMapMarkers(networkData.value.nodes)
      updateNetworkChart(networkData.value)
      
      ElMessage({
        message: `成功加载了 ${networkData.value.nodes.length} 个设施和 ${networkData.value.links.length} 条连接`,
        type: 'success'
      })
    }
  } catch (err) {
    console.error('加载网络数据失败:', err)
    error.value = `加载网络数据失败: ${err.message || '未知错误'}`
    
    // 尝试使用getInitialData直接获取初始数据
    try {
      console.log('尝试获取初始数据...')
      const initialResponse = await getInitialData()
      console.log('初始数据响应:', initialResponse)
      
      let initialData = null
      // 处理响应结构
      if (initialResponse.data !== undefined) {
        initialData = initialResponse.data
      } else {
        initialData = initialResponse
      }
      
      // 验证数据结构
      if (!initialData || !Array.isArray(initialData.nodes) || !Array.isArray(initialData.links)) {
        throw new Error('初始数据格式不正确')
      }
      
      // 数据后处理
      initialData.nodes = initialData.nodes.map(node => {
        // 确保节点有category属性
        if (node.category === undefined && node.facility_type !== undefined) {
          const categoryMap = {
            'import': 0,
            'refinery': 1,
            'storage': 2,
            'airport': 3
          }
          node.category = categoryMap[node.facility_type] || 0
        }
        
        // 确保节点有value属性
        if (node.value === undefined && node.capacity !== undefined) {
          node.value = node.capacity
        }
        
        return node
      })
      
      networkData.value = initialData
      
      // 更新图表
      await nextTick()
      if (!mapInstance) {
        initMap()
      }
      if (!networkChart) {
        initNetworkChart()
      }
      
      // 更新地图标记和网络图
      updateMapMarkers(networkData.value.nodes)
      updateNetworkChart(networkData.value)
      
      ElMessage({
        message: `已加载初始数据: ${networkData.value.nodes.length} 个设施和 ${networkData.value.links.length} 条连接`,
        type: 'warning'
      })
    } catch (initialError) {
      console.error('初始数据加载失败:', initialError)
      
      // 如果两种方式都失败，使用本地静态数据
      try {
        console.log('使用本地静态数据作为最后的回退...')
        const staticData = {
          nodes: [
            { id: 1, name: '台北港', value: 250, category: 0, facility_type: 'import', region: 'taipei', latitude: 25.15, longitude: 121.18 },
            { id: 2, name: '台北炼油厂', value: 180, category: 1, facility_type: 'refinery', region: 'taipei', latitude: 25.04, longitude: 121.5 },
            { id: 3, name: '桃园油库', value: 120, category: 2, facility_type: 'storage', region: 'taipei', latitude: 24.99, longitude: 121.3 },
            { id: 4, name: '台北机场', value: 80, category: 3, facility_type: 'airport', region: 'taipei', latitude: 25.08, longitude: 121.55 }
          ],
          links: [
            { source: 1, target: 2 },
            { source: 2, target: 3 },
            { source: 3, target: 4 }
          ],
          categories: [
            { name: '原油进口设施' },
            { name: '炼油厂' },
            { name: '区域存储油库' },
            { name: '机场油库' }
          ]
        }
        
        networkData.value = staticData
        
        // 更新图表
        await nextTick()
        if (!mapInstance) {
          initMap()
        }
        if (!networkChart) {
          initNetworkChart()
        }
        
        // 更新地图标记和网络图
        updateMapMarkers(networkData.value.nodes)
        updateNetworkChart(networkData.value)
        
        ElMessage({
          message: '使用本地静态数据',
          type: 'warning'
        })
      } catch (staticError) {
        console.error('静态数据加载失败:', staticError)
        ElMessage.error('无法加载任何油料设施数据，请检查网络连接或联系系统管理员')
      }
    }
  } finally {
    loading.value = false
  }
}

// 初始化测试数据
const initTestDatabase = async () => {
  loading.value = true
  error.value = ''
  
  try {
    console.log('正在初始化测试数据库...')
    const result = await initTestData()
    console.log('初始化测试数据库结果:', result)
    
    if (result.success) {
      ElMessage.success('测试数据库初始化成功，正在加载数据...')
      // 初始化成功后重新加载数据
      await loadNetworkData()
    } else {
      throw new Error('初始化测试数据库失败')
    }
  } catch (err) {
    console.error('初始化测试数据库失败:', err)
    error.value = `初始化测试数据库失败: ${err.message || '未知错误'}`
    ElMessage.error('无法初始化测试数据库')
  } finally {
    loading.value = false
  }
}

// 查询按钮处理
const handleQuery = async () => {
  await loadNetworkData()
}

// 添加初始化测试数据按钮的处理函数
const handleInitTestData = async () => {
  await initTestDatabase()
}

// 高亮设施
const highlightFacility = async (facilityId) => {
  if (!facilityId) {
    error.value = '未指定设施ID'
    return
  }
  
  if (loading.value) {
    return
  }
  
  loading.value = true
  error.value = ''
  
  try {
    console.log(`请求追踪设施供应链，ID: ${facilityId}`)
    const response = await traceSupplyChain(facilityId)
    console.log('追踪响应:', response)
    
    let traceData = null
    // 处理两种可能的响应结构
    if (response.data !== undefined) {
      // 结构: { data: { nodes, links, facility } }
      traceData = response.data
    } else {
      // 结构: { nodes, links, facility }
      traceData = response
    }
    
    // 验证数据格式
    if (!traceData || !Array.isArray(traceData.nodes) || !Array.isArray(traceData.links)) {
      throw new Error('无效的追踪数据格式')
    }
    
    if (!traceData.facility) {
      throw new Error(`未找到ID为${facilityId}的设施`)
    }
    
    // 处理facility对象 - 确保有正确的属性
    const facility = traceData.facility
    if (facility.value === undefined && facility.capacity !== undefined) {
      facility.value = facility.capacity
    }
    
    // 设置当前追踪的设施
    tracedFacility.value = facility
    
    // 获取节点ID列表
    const highlightedNodeIds = traceData.nodes.map(node => node.id)
    console.log('高亮的节点IDs:', highlightedNodeIds)
    
    // 更新网络图和地图标记的高亮状态
    updateNetworkChart(networkData.value, highlightedNodeIds)
    updateMapMarkers(networkData.value.nodes, highlightedNodeIds)
    
    // 设置高亮状态
    isHighlighted.value = true
    
    ElMessage({
      message: `成功追踪设施 ${traceData.facility.name} 的供应链关系`,
      type: 'success'
    })
  } catch (err) {
    console.error('追踪设施供应链失败:', err)
    error.value = `追踪设施供应链失败: ${err.message || '未知错误'}`
    ElMessage.error('无法完成设施追踪')
  } finally {
    loading.value = false
  }
}

// 重置高亮
const resetHighlight = () => {
  try {
    // 重置追踪的设施
    tracedFacility.value = null
    
    // 重置网络图高亮
    if (networkChart) {
      networkChart.setOption({
        series: [{
          data: networkData.value.nodes.map(node => {
            return {
              ...node,
              itemStyle: {
                opacity: 1
              },
              label: {
                show: false
              }
            }
          }),
          links: networkData.value.links.map(link => {
            return {
              ...link,
              lineStyle: {
                opacity: 0.5,
                color: '#bbb'
              }
            }
          })
        }]
      })
    }
    
    // 清除地图标记层上的高亮
    if (mapInstance && markersLayer) {
      markersLayer.eachLayer(layer => {
        // 重置图标样式
        const defaultIcon = new L.Icon.Default();
        if (layer.setIcon) {
          layer.setIcon(defaultIcon);
        }
        // 移除弹出窗口
        if (layer.closePopup) {
          layer.closePopup();
        }
      });
    }
    
    // 重置高亮状态
    isHighlighted.value = false
    
    // 清除错误消息
    error.value = ''
    
    ElMessage({
      message: '已重置所有高亮',
      type: 'success'
    })
  } catch (err) {
    console.error('重置高亮时出错:', err)
    error.value = `重置高亮时出错: ${err.message || '未知错误'}`
    ElMessage.error('重置高亮时出错')
  }
}

// 生命周期钩子
onMounted(async () => {
  try {
    console.log('组件已挂载，开始初始化...');
    
    // 初始化窗口调整事件
    window.addEventListener('resize', handleWindowResize);
    
    // 先初始化图表实例
    await nextTick();
    initMap();
    initNetworkChart();
    
    // 再加载网络数据
    await loadNetworkData();
    
    console.log('组件初始化完成');
  } catch (err) {
    console.error('组件初始化失败:', err);
    error.value = `组件初始化失败: ${err.message || '未知错误'}`;
    ElMessage.error('应用初始化失败');
  }
});

// 窗口调整
const handleWindowResize = () => {
  try {
    // 调整地图大小
    if (mapInstance) {
      mapInstance.invalidateSize();
    }
    
    // 调整网络图大小
    if (networkChart) {
      networkChart.resize();
    }
  } catch (err) {
    console.error('窗口大小调整时出错:', err);
  }
};

// 组件卸载时清理
onUnmounted(() => {
  // 移除窗口调整事件
  window.removeEventListener('resize', handleWindowResize);
  
  // 销毁地图实例
  if (mapInstance) {
    mapInstance.remove();
    mapInstance = null;
  }
  
  // 销毁图表实例
  if (networkChart) {
    networkChart.dispose();
    networkChart = null;
  }
});

// 监听布局变化
watch(() => queryForm.value.layout, () => {
  if (networkChart && networkData.value) {
    networkChart.setOption({
      series: [{
        name: '油料供应',
        layout: queryForm.value.layout
      }]
    })
  }
})
</script>

<style scoped>
.analysis-container {
  padding: 20px;
  height: 100vh;
  overflow: hidden;
}

.query-panel {
  height: calc(100vh - 40px);
  overflow-y: auto;
}

.map-container, .network-container {
  height: calc(100vh - 40px);
}

.chart {
  width: 100%;
  height: calc(100% - 60px);
}

#mapChart, #networkChart {
  min-height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.legend {
  display: flex;
  gap: 15px;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.color-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 5px;
}

.facility-detail {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.facility-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.facility-info {
  font-size: 14px;
}

.info-item {
  display: flex;
  margin-bottom: 5px;
}

.label {
  width: 90px;
  color: #606266;
}

.value {
  flex: 1;
  color: #303133;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 123, 255, 0.2);
  border-radius: 50%;
  border-top-color: #007bff;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.layout-switch {
  display: flex;
  align-items: center;
}

.layout-label {
  margin-right: 10px;
  font-size: 13px;
  color: #606266;
}

:deep(.el-card__body) {
  position: relative;
  padding: 15px;
}

:deep(.facility-tooltip) {
  font-size: 12px;
  padding: 5px 8px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  border-radius: 4px;
}

/* 添加错误消息样式 */
.error-message {
  margin: 10px 0;
}

.error-message .el-alert {
  margin-bottom: 10px;
}
</style>